package com.example.demo.others.jenkins;

import com.alibaba.fastjson.JSONObject;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import com.offbytwo.jenkins.model.Job;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017-6-9.
 */
public class JenkinsUtil {

    static Logger logger = LoggerFactory.getLogger(JenkinsUtil.class);





    public static void job(Job job, Map<String, String> params) throws Exception {


        JenkinsHttpClient c = job.getClient();
//            logger.info("{},{}", job.getUrl(), job.getName());

        if (StringUtils.isNotBlank(params.get("clean"))) {

            logger.info("-----------clean workspace-------------");
            c.post(job.getUrl() + "/doWipeOutWorkspace", true);
        }else {
            logger.info("-----------don't clean workspace-------------");

        }
        c.post(job.getUrl() + "/build?delay=0sec" + buildParams(params), true);


//            logger.info("qr:{}", 1);


    }




    public static String buildParams(Map<String, String> map) {

        JSONObject j = new JSONObject();


        j.put("statusCode", "303");
        j.put("redirectTo", ".");
        j.put("Jenkins-Crumb", "XX");


        List<JSONObject> list = new ArrayList<>();

        StringBuilder sb1 = new StringBuilder();

        String[] vs = map.get("val").split(",");
        String[] ks = map.get("key").split(",");
        if (vs != null && vs.length > 0) {

            for (int i = 0; i < vs.length; ++i) {

                if (StringUtils.isBlank(ks[i]) || StringUtils.isBlank(vs[i])) continue;

                sb1.append("&" + ks[i] + "=" + encode(vs[i]));


                JSONObject jj = new JSONObject();
                jj.put("name", ks[i]);
                jj.put("value", vs[i]);
                list.add(jj);


            }
        }


        j.put("Submit", encode("开始构建"));


        JSONObject par = new JSONObject();
        par.put("parameter", list);
        par.put("statusCode", "303");
        par.put("redirectTo", ".");
        par.put("Jenkins-Crumb", "XX");


        j.put("json", encode(par.toJSONString()));

        StringBuilder sb = new StringBuilder();
        j.forEach((k, v) -> {

            sb.append("&" + k + "=" + v);

        });

        System.out.println(sb + "" + sb1);

        return sb1.toString() + sb.toString();


    }


    public static String encode(String val) {
        try {

            return URLEncoder.encode(val, "utf-8");
        } catch (Exception e) {

            e.printStackTrace();
        }
        return "";
    }


}
